<template>
  <div class="list-container">
    <van-nav-bar
      title="热门推荐"
      left-text="返回"
      left-arrow
      fixed
      placeholder
      @click-left="clickToBack"
      @click-right="clickToSearch"
    >
      <template #right>
        <van-icon name="search" size="18" />
      </template>
    </van-nav-bar>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        class="px-4 pt-4"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <detail-card
          class="mb-4"
          v-for="item in list"
          :key="item.id"
          :id="item.id"
          :name="item.name"
          :image="item.image"
          :writer="item.writer"
          :is_over="item.is_over"
          :intro="item.intro"
          :type="item.type"
        ></detail-card>
      </van-list>
    </van-pull-refresh>
    <BackToTop />
  </div>
</template>
<script lang="ts" setup>
import { ref, Ref } from 'vue'
import { useRouter } from 'vue-router'
import DetailCard from '@/components/DetailCard/DetailCard.vue'
import { getOverList } from '@/api/homepage'
import { BookItem } from '@/common/types'
import BackToTop from '@/components/BackToTop/BackToTop.vue'

const list: Ref<BookItem[]> = ref([])
const loading = ref(false)
const finished = ref(false)
const error = ref(false)
const refreshing = ref(false)

let page: number = 1
const pageSize: number = 20

const onLoad = () => {
  if (loading.value) return
  loading.value = true
  getOverList({ page, pageSize })
    .then((res) => {
      if (res.data.list.length === 0) {
        finished.value = true
      }
      loading.value = false
      list.value = [...list.value, ...res.data.list]
      page += 1
    })
    .catch((e) => {
      error.value = true
    })
}
const onRefresh = () => {
  if (loading.value) return
  finished.value = false
  loading.value = true
  page = 1
  list.value = []
  getOverList({ page, pageSize })
    .then((res) => {
      if (res.data.list.length === 0) {
        finished.value = true
      }
      loading.value = false
      refreshing.value = false
      list.value = [...list.value, ...res.data.list]
      page += 1
    })
    .catch((e) => {
      error.value = true
    })
}

const router = useRouter()
const clickToBack = () => {
  router.back()
}

const clickToSearch = () => {
  router.push({ name: 'Search' })
}
</script>
<style scoped>
.list-container {
  min-height: 100vh;
}
</style>
